import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:flutter_taotaoshipin/widget/my_app_bar.dart';
import 'package:get/get.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import 'feedback_controller.dart';

class FeedbackPage extends StatefulWidget {
  const FeedbackPage({Key? key}) : super(key: key);

  @override
  State<FeedbackPage> createState() => _FeedbackPageState();
}

class _FeedbackPageState extends State<FeedbackPage> {
  final controller = Get.find<FeedbackController>();
  final state = Get.find<FeedbackController>().state;

  final feedbackNode = FocusNode();
  final phoneNode = FocusNode();

  @override
  void dispose() {
    feedbackNode.dispose();
    phoneNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(centerTitle: '投诉反馈'),
      body: GetBuilder<FeedbackController>(builder: (controller) {
        return KeyboardActions(
          config: KeyboardActionsConfig(
            actions: [
              KeyboardActionsItem(focusNode: feedbackNode),
              KeyboardActionsItem(focusNode: phoneNode),
            ],
          ),
          child: Column(
            children: [
              _buildFeedback(),
              _buildContact(),
              _buildSnapshot(),
              SizedBox(height: 39),
              _buildSubmitButton(),
            ],
          ),
        );
      }),
    );
  }

  _buildFeedback() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.fromLTRB(16, 25, 16, 15),
      child: Column(
        children: [
          Row(
            children: [
              LoadAssetImage(
                'me/feedback/question',
                width: 20,
                height: 20,
              ),
              SizedBox(width: 8),
              Text(
                '问题描述',
                style: TextStyle(
                  color: Color(0xFF2D2D2D),
                  fontSize: 17,
                  fontWeight: FontWeight.w900,
                ),
              ),
              Spacer(),
            ],
          ),
          SizedBox(height: 15),
          Container(
            height: 204,
            padding: EdgeInsets.all(15),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: [
                Expanded(
                  child: TextField(
                    focusNode: feedbackNode,
                    controller: controller.feedbackEditingController,
                    maxLines: 8,
                    maxLength: 200,
                    keyboardType: TextInputType.multiline,
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.black,
                    ),
                    decoration: InputDecoration(
                      isCollapsed: true,
                      isDense: true,
                      hintText: '请写下您的问题，我们会努力解决（必填）',
                      hintStyle: TextStyle(
                        color: Color(0xFF999999),
                        fontSize: 14,
                      ),
                      counterText: '',
                      border: InputBorder.none,
                    ),
                  ),
                ),
                Row(
                  children: [
                    Spacer(),
                    Text(
                      '${controller.feedbackEditingController.text.length}/200',
                      style: TextStyle(
                        color: Color(0xFF999999),
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _buildSnapshot() {
    double photoWidth = (Get.mediaQuery.size.width - 16 * 2 - 10 * 3) / 4;
    return Container(
      padding: EdgeInsets.fromLTRB(16, 15, 16, 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              LoadAssetImage(
                'me/feedback/image',
                width: 20,
                height: 20,
              ),
              SizedBox(width: 8),
              Text(
                '上传图片',
                style: TextStyle(
                  color: Color(0xFF2D2D2D),
                  fontSize: 17,
                  fontWeight: FontWeight.w900,
                ),
              ),
              Spacer(),
              // Text(
              //   '${state.images.length}/4',
              //   style: TextStyle(
              //     color: Color.fromARGB(255, 47, 47, 47),
              //     fontSize: 13,
              //   ),
              // ),
            ],
          ),
          SizedBox(height: 10),
          Wrap(
            spacing: 10,
            children: [
              ...List.generate(
                state.images.length,
                (index) {
                  return _buildPhoto(
                    photoWidth: photoWidth,
                    entity: state.images[index],
                    removeCallback: () {
                      controller.removeImageAt(index);
                    },
                  );
                },
              ),
              if (state.images.length < 4)
                InkWell(
                  onTap: () {
                    controller.addImages();
                  },
                  child: Padding(
                    padding: const EdgeInsets.only(top: 10),
                    child: Container(
                      width: photoWidth,
                      height: photoWidth,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Icon(
                        Icons.add,
                        size: 32,
                        color: Color(0xFFCACACA),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  _buildContact() {
    return Container(
      padding: EdgeInsets.fromLTRB(16, 15, 16, 15),
      child: Column(
        children: [
          Row(
            children: [
              LoadAssetImage(
                'me/feedback/contact',
                width: 20,
                height: 20,
              ),
              SizedBox(width: 8),
              Text(
                '联系方式',
                style: TextStyle(
                  color: Color(0xFF2D2D2D),
                  fontSize: 17,
                  fontWeight: FontWeight.w900,
                ),
              ),
              Spacer(),
            ],
          ),
          SizedBox(height: 15),
          Container(
            padding: EdgeInsets.all(15),
            height: 50,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: TextField(
              focusNode: phoneNode,
              controller: controller.phoneEditingController,
              style: TextStyle(
                fontSize: 14,
              ),
              decoration: InputDecoration(
                isCollapsed: true,
                isDense: true,
                hintText: '请输入您的联系方式（必填）',
                hintStyle: TextStyle(
                  color: Color(0xFFBCBCBC),
                  fontSize: 14,
                ),
                counterText: '',
                border: InputBorder.none,
              ),
            ),
          ),
        ],
      ),
    );
  }

  _buildSubmitButton() {
    return InkWell(
      onTap: () {
        if (controller.feedbackEditingController.text.trim().isEmpty) {
          EasyLoading.showError('问题反馈不能为空');
        } else if (controller.phoneEditingController.text.trim().isEmpty) {
          EasyLoading.showError('联系方式不能为空');
        } else {
          controller.submitButtonClicked();
        }
      },
      child: Container(
        width: double.infinity,
        height: 50,
        margin: EdgeInsets.symmetric(horizontal: 17),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [
              Color(0xFF7AB3FF),
              Color(0xFF2760FF),
            ],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
          boxShadow: [
            BoxShadow(
              color: Color(0x993972FF),
              offset: Offset(0, 5),
              blurRadius: 10,
            ),
          ],
          borderRadius: BorderRadius.circular(10),
        ),
        child: Text(
          '提交',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w900,
          ),
        ),
      ),
    );
  }

  _buildPhoto({
    required double photoWidth,
    required AssetEntity entity,
    Function()? removeCallback,
  }) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Padding(
          padding: const EdgeInsets.only(top: 10),
          child: Container(
            width: photoWidth,
            height: photoWidth,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(7),
              color: Color.fromARGB(255, 245, 246, 247),
            ),
            clipBehavior: Clip.hardEdge,
            child: AssetEntityImage(
              entity,
              isOriginal: false,
              fit: BoxFit.cover,
            ),
          ),
        ),
        Positioned(
          top: 0,
          right: 0,
          child: InkWell(
            onTap: removeCallback,
            child: LoadAssetImage(
              'me/feedback/photo_del',
              width: 18,
              height: 18,
            ),
          ),
        ),
      ],
    );
  }
}
